import dayjs from "dayjs";
import isToday from "dayjs/plugin/isToday";
import { PxButton, PxInput } from "px-ui";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

dayjs.extend(isToday);

export const formatSpanFn = (data: Array<any>): Array<any> => {
  if (!data?.length) return [];
  let currentGasNameNum = 0;
  let currentStationNum = 0;
  let currentGasName = "";
  let currentGasNameIndex = 0;
  data?.forEach((item, index, arr) => {
    const { gasName, station } = item;
    if (index === 0) {
      currentGasName = gasName;
      currentGasNameIndex = 0;
    } else if (gasName !== currentGasName) {
      currentGasName = gasName;
      currentGasNameIndex++;
    }
    item["index"] = currentGasNameIndex;
    currentGasNameNum++;
    currentStationNum++;
    if (gasName !== arr[index + 1]?.gasName) {
      data[index - currentGasNameNum + 1]["rowspan"] = currentGasNameNum;
      currentGasNameNum = 0;
      data[index - currentStationNum + 1]["rowspan2"] = currentStationNum;
      currentStationNum = 0;
    } else {
      if (station !== arr[index + 1]?.station) {
        data[index - currentStationNum + 1]["rowspan2"] = currentStationNum;
        currentStationNum = 0;
      }
    }
  });
  return data;
};

export const formatBottomTableDataFn = (
  formatSpanData: Array<any>,
  gasCheckInfoResDTOList: Array<any>,
  scheduleEmployeeInfoDTOList: Array<any>,
  cb?: (name: string, value: number) => void
) => {
  const inspectionPerson = {
    gasName: "点检人",
    isInspectionPerson: true,
    isFixed: true,
    scheduleEmployeeInfoDTOList
  };
  const systemEngineer = {
    gasName: "系统工程师",
    isSystemEngineer: true,
    isFixed: true,
    scheduleEmployeeInfoDTOList
  };
  const mixedAcidTimesLabel = {
    gasName: "混酸次数",
    isMixedAcidTimesLabel: true,
    isFixed: true,
    scheduleEmployeeInfoDTOList
  };
  const mixedAcidTimesValue = {
    gasName: "混酸次数",
    isMixedAcidTimesValue: true,
    isFixed: true,
    scheduleEmployeeInfoDTOList
  };

  formatSpanData[0]?.dayValues?.forEach((item, index) => {
    const { planTimeDayStr = "" } = item;
    const t = gasCheckInfoResDTOList?.find(item => item?.itemDate === planTimeDayStr);
    if (t) {
      const { checkerInfo = null, engineerInfo = null, mixAcidInfoList = [], itemDate = "" } = t;
      const checkerInfoArr = [checkerInfo?.operator, checkerInfo?.operatorName]?.filter(item => !!item);
      const engineerInfoArr = [engineerInfo?.operator, engineerInfo?.operatorName]?.filter(item => !!item);
      inspectionPerson[`readValue_f_${index}`] =
        checkerInfoArr.length === 2 ? checkerInfoArr.join(" / ") : checkerInfoArr.length === 1 ? checkerInfoArr[0] : "";
      systemEngineer[`readValue_f_${index}`] =
        engineerInfoArr.length === 2 ? engineerInfoArr.join(" / ") : engineerInfoArr.length === 1 ? engineerInfoArr[0] : "";
      if (dayjs(itemDate).isToday()) {
        inspectionPerson["systemEngineerName"] =
          engineerInfoArr.length === 2 ? engineerInfoArr.join(" / ") : engineerInfoArr.length === 1 ? engineerInfoArr[0] : "";
        inspectionPerson["inspectionPersonKey"] = `readValue_f_${index}`;
        inspectionPerson["itemDate"] = itemDate;
        systemEngineer["inspectionPersonName"] =
          checkerInfoArr.length === 2 ? checkerInfoArr.join(" / ") : checkerInfoArr.length === 1 ? checkerInfoArr[0] : "";
        systemEngineer["systemEngineerKey"] = `readValue_f_${index}`;
        systemEngineer["itemDate"] = itemDate;
        mixedAcidTimesValue["mixedAcidTimesValueKeys"] = [`readValue_f_${index}`, `placeholder_s_1_${index}`, `placeholder_t_2_${index}`];
        mixedAcidTimesValue["inspectionPersonName"] =
          checkerInfoArr.length === 2 ? checkerInfoArr.join(" / ") : checkerInfoArr.length === 1 ? checkerInfoArr[0] : "";
        mixedAcidTimesValue["systemEngineerName"] =
          engineerInfoArr.length === 2 ? engineerInfoArr.join(" / ") : engineerInfoArr.length === 1 ? engineerInfoArr[0] : "";
      }

      for (const item of mixAcidInfoList) {
        const { chemicalName, mixAcidCounts } = item;
        cb && cb(chemicalName, mixAcidCounts);
        if (!(`readValue_f_${index}` in mixedAcidTimesLabel)) {
          mixedAcidTimesLabel[`readValue_f_${index}`] = chemicalName;
        } else if (!(`placeholder_s_1_${index}` in mixedAcidTimesLabel)) {
          mixedAcidTimesLabel[`placeholder_s_1_${index}`] = chemicalName;
        } else if (!(`placeholder_t_2_${index}` in mixedAcidTimesLabel)) {
          mixedAcidTimesLabel[`placeholder_t_2_${index}`] = chemicalName;
        }
        if (!(`readValue_f_${index}` in mixedAcidTimesValue)) {
          mixedAcidTimesValue[`readValue_f_${index}`] = mixAcidCounts;
        } else if (!(`placeholder_s_1_${index}` in mixedAcidTimesValue)) {
          mixedAcidTimesValue[`placeholder_s_1_${index}`] = mixAcidCounts;
        } else if (!(`placeholder_t_2_${index}` in mixedAcidTimesValue)) {
          mixedAcidTimesValue[`placeholder_t_2_${index}`] = mixAcidCounts;
        }
      }
    }
  });
  return [mixedAcidTimesLabel, mixedAcidTimesValue, inspectionPerson, systemEngineer];
};

export const formatTableDataFn = (res: Record<string, any>, cb?: (name: string, value: number) => void): Array<any> => {
  const { recordItemResDTOList, gasCheckInfoResDTOList, scheduleEmployeeInfoDTOList } = res;
  if (!recordItemResDTOList?.length) return [];
  const formatData = recordItemResDTOList?.map(item => {
    const { dayValues = [], station = "" } = item;
    const ext = dayValues?.reduce((pre, cur, index) => {
      const { supplyStatusL = "", supplyStatusR = "", valueDayHourList = [] } = cur;
      const fd = valueDayHourList?.filter(item => item.groupCode === "GAS_CHEMICAL_CHECK_FIVE"); // 过滤当天 5：00
      const sd = valueDayHourList?.filter(item => item.groupCode === "GAS_CHEMICAL_CHECK_SEVENTEEN"); // 过滤当天 17：00
      const td = valueDayHourList?.filter(item => item.groupCode === "GAS_CHEMICAL_CHECK_TWENTY_ONE"); // 过滤当天 21：00
      pre[`readValue_f_${index}`] = fd[0]?.readValue;
      pre[`placeholder_f_1_${index}`] = "";
      pre[`placeholder_f_2_${index}`] = "";
      pre[`readValue_s_${index}`] = sd[0]?.readValue;
      pre[`placeholder_s_1_${index}`] = "";
      pre[`placeholder_s_2_${index}`] = "";
      pre[`readValue_t_${index}`] = td[0]?.readValue;
      pre[`placeholder_t_1_${index}`] = "";
      pre[`placeholder_t_2_${index}`] = "";
      pre[`supplyStatus_${index}`] = station === "L" ? supplyStatusL : station === "R" ? supplyStatusR : "";
      pre[`placeholder_ss_1_${index}`] = "";
      pre[`placeholder_ss_2_${index}`] = "";
      return pre;
    }, {});
    return { ...item, ...ext };
  });
  const formatSpanData = formatSpanFn(formatData);
  const formatBottomTableData = formatBottomTableDataFn(formatSpanData, gasCheckInfoResDTOList, scheduleEmployeeInfoDTOList, cb);
  return [...formatSpanData, ...formatBottomTableData];
};

export const formatDateTableCloumnsFn = (
  data: Array<any>,
  cb?: (scope: any) => void,
  cb2?: (scope: any) => void,
  cb3?: (name: string, value: number) => void
): Array<any> => {
  if (!data?.length) return [];
  return data[0]?.dayValues?.reduce((pre, cur, index) => {
    const { planTimeDayStr: label = "", valueDayHourList = [] } = cur;
    const fd = valueDayHourList?.filter(item => item.groupCode === "GAS_CHEMICAL_CHECK_FIVE"); // 过滤当天 5：00
    const sd = valueDayHourList?.filter(item => item.groupCode === "GAS_CHEMICAL_CHECK_SEVENTEEN"); // 过滤当天 17：00
    const td = valueDayHourList?.filter(item => item.groupCode === "GAS_CHEMICAL_CHECK_TWENTY_ONE"); // 过滤当天 21：00
    let mixedAcidTimesLabelData = {};
    const render = scope => {
      const {
        row: {
          isInspectionPerson = false,
          isSystemEngineer = false,
          isMixedAcidTimesLabel = false,
          isMixedAcidTimesValue = false,
          inspectionPersonKey = "",
          systemEngineerKey = "",
          mixedAcidTimesValueKeys = [],
          scheduleEmployeeInfoDTOList = [],
          inspectionPersonName = "",
          systemEngineerName = ""
        },
        column: { property = "" }
      } = scope;
      const styleFn = () => {
        const textAlign = "center";
        const fontWeight = 600;
        return { textAlign, fontWeight };
      };
      const styleFn2 = () => {
        const textAlign = "left";
        const fontWeight = undefined;
        return { textAlign, fontWeight };
      };
      const styleFn3 = () => {
        return {
          display: "flex",
          alignItems: "center",
          justifyContent: "center"
        };
      };
      const userInfo = localStorage.getItem("userInfo");
      const { userId = null } = JSON.parse(userInfo);
      if (isInspectionPerson || isSystemEngineer) {
        if (inspectionPersonKey === property) {
          return () =>
            scope.row[property] && systemEngineerName ? (
              <div style={styleFn()}>{scope.row[property] || "--"}</div>
            ) : (
              <div style={styleFn()}>
                <PxButton
                  type="primary"
                  size="small"
                  disabled={!scheduleEmployeeInfoDTOList?.some(item => item.userId === Number(userId))}
                  vHas={"GAS_CONSUMPTION_CHEMICAL_INSPECTION_BTN"}
                  onClick={useThrottleFn(() => cb && cb(scope), delay)}
                >
                  {"点检"}
                </PxButton>
              </div>
            );
        } else if (systemEngineerKey === property) {
          return () =>
            scope.row[property] ? (
              <div style={styleFn()}>{scope.row[property] || "--"}</div>
            ) : (
              <div style={styleFn()}>
                <PxButton
                  type="primary"
                  size="small"
                  disabled={!inspectionPersonName}
                  vHas={"GAS_CONSUMPTION_CHEMICAL_INSPECTION_CONFIRM_BTN"}
                  onClick={useThrottleFn(() => cb2 && cb2(scope), delay)}
                >
                  {"确认"}
                </PxButton>
              </div>
            );
        } else {
          return () => <div style={styleFn()}>{scope.row[property] || "--"}</div>;
        }
      } else if (isMixedAcidTimesLabel) {
        mixedAcidTimesLabelData = { ...mixedAcidTimesLabelData, ...scope.row };
        return () => <div style={styleFn()}>{scope.row[property] || "--"}</div>;
      } else if (isMixedAcidTimesValue) {
        if (mixedAcidTimesValueKeys?.includes(property)) {
          if (systemEngineerName) {
            return () => <div style={styleFn()}>{scope.row[property] || "--"}</div>;
          } else {
            return () => (
              <div style={styleFn3()}>
                <PxInput
                  vModel={scope.row[property]}
                  type="number"
                  class="px-input-number-no-controls"
                  disabled={!scheduleEmployeeInfoDTOList?.some(item => item.userId === Number(userId))}
                  vHas={"GAS_CONSUMPTION_CHEMICAL_INSPECTION_BTN"}
                  size="small"
                  min={0}
                  clearable={true}
                  placeholder={`请输入混酸次数${mixedAcidTimesLabelData[property]}`}
                  onChange={(val: string | number) => cb3(mixedAcidTimesLabelData[property] || "", val as number)}
                />
              </div>
            );
          }
        } else {
          return () => <div style={styleFn()}>{scope.row[property] || "--"}</div>;
        }
      } else {
        return () => <div style={styleFn2()}>{scope.row[property] ?? "--"}</div>;
      }
    };

    const f = {
      label: fd[0]?.planTimeHourStr,
      prop: `readValue_f_${index}`,
      width: 30,
      render
    };
    const p_f_1 = {
      label: "p_f_1",
      prop: `placeholder_f_1_${index}`,
      width: 30
    };
    const p_f_2 = {
      label: "p_f_2",
      prop: `placeholder_f_2_${index}`,
      width: 30
    };
    // const f_h = {
    //   label: fd[0]?.planTimeHourStr,
    //   prop: `readValue_f_${index}`,
    //   children: [f, p_f_1, p_f_2]
    // };

    const s = {
      label: sd[0]?.planTimeHourStr,
      prop: `readValue_s_${index}`,
      width: 30
    };
    const p_s_1 = {
      label: "p_s_1",
      prop: `placeholder_s_1_${index}`,
      width: 30,
      render
    };
    const p_s_2 = {
      label: "p_s_2",
      prop: `placeholder_s_2_${index}`,
      width: 30
    };
    // const s_h = {
    //   label: sd[0]?.planTimeHourStr,
    //   prop: `readValue_s_${index}`,
    //   children: [s, p_s_1, p_s_2]
    // };

    const t = {
      label: td[0]?.planTimeHourStr,
      prop: `readValue_t_${index}`,
      width: 30
    };
    const p_t_1 = {
      label: "p_t_1",
      prop: `placeholder_t_1_${index}`,
      width: 30
    };
    const p_t_2 = {
      label: "p_t_2",
      prop: `placeholder_t_2_${index}`,
      width: 30,
      render
    };
    // const t_h = {
    //   label: td[0]?.planTimeHourStr,
    //   prop: `readValue_t_${index}`,
    //   children: [t, p_t_1, p_t_2]
    // };

    const children = [f, p_f_1, p_f_2, s, p_s_1, p_s_2, t, p_t_1, p_t_2];
    const prop = "planTimeDayStr";
    const renderHeader = () => {
      return () => <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>{label}</div>;
    };
    const d = { label, prop, renderHeader };
    d["children"] = children;
    pre.push(d);

    const status = {
      label: "供应状态",
      prop: `supplyStatus_${index}`,
      width: 30
    };
    const p_ss_1 = {
      label: "p_ss_1",
      prop: `placeholder_ss_1_${index}`,
      width: 30
    };
    const p_ss_2 = {
      label: "p_ss_2",
      prop: `placeholder_ss_2_${index}`,
      width: 30
    };

    // const status_h = {
    //   label: "供应状态",
    //   prop: `supplyStatus_${index}`,
    //   children: [status, p_ss_1, p_ss_2]
    // };

    pre.push(status, p_ss_1, p_ss_2);
    return pre;
  }, []);
};
